import React from 'react'
import { BackHandler } from 'react-native'

/**
 * Android物理返回键处理
 * https://reactnavigation.org/docs/en/redux-integration.html#handling-the-hardware-back-button-in-android
 */
export default class BackPressComponent {
	constructor(props) {
		this._hardwareBackPress = this.onHardwareBackPress.bind(this)
		this.props = props
	}

	componentDidMount() {
		if (this.props.backPress) {
			BackHandler.addEventListener(
				'hardwareBackPress',
				this._hardwareBackPress
			)
		}
	}

	componentWillUnmount() {
		if (this.props.backPress) {
			BackHandler.removeEventListener(
				'hardwareBackPress',
				this._hardwareBackPress
			)
		}
	}

	onHardwareBackPress(e) {
		return this.props.backPress(e)
	}
}
